
from flask import Flask, render_template, request, redirect, url_for
import pymysql
import pymysql.cursors
import datetime as dt

app = Flask(__name__,template_folder='')

# 数据库连接配置
db_config = {
    'host': 'localhost',
    'user': 'root',
    'password': '111111',
    'database': 'meijiaxue',
    'charset': 'utf8mb4',
    'cursorclass': pymysql.cursors.DictCursor
}

@app.route('/')
def index():
    # 连接到数据库
    connection = pymysql.connect(**db_config)
    try:
        with connection.cursor() as cursor:
            sql = "SELECT * FROM diary_entries ORDER BY date DESC"
            cursor.execute(sql)
            result = cursor.fetchall()
        return render_template('index.html', entries=result)
    finally:
        connection.close()

@app.route('/submit', methods=['POST'])
def submit():
    date = request.form['date']
    weather = request.form['weather']
    mood = request.form['mood']
    event = request.form['event']

    # 连接到数据库
    connection = pymysql.connect(**db_config)
    try:
        with connection.cursor() as cursor:
            sql = "INSERT INTO diary_entries (date, weather, mood, event) VALUES (%s, %s, %s, %s)"
            cursor.execute(sql, (date, weather, mood, event))
        connection.commit()
    finally:
        connection.close()

    return redirect(url_for('index'))

if __name__ == '__main__':
    app.run(host='0.0.0.0',debug=True)